/*
 * Copyright 2009 Gal Dolber
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package com.google.gwt.user.client.ui;

import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.Event.NativePreviewEvent;
import com.google.gwt.user.client.Event.NativePreviewHandler;

/**
 * Widget that follows the mouse TODO stack
 */
public class MouseFollower extends SimplePanel {

	static MouseFollower mouseElement = new MouseFollower();

	/**
	 * Hides the mouse element
	 */
	public static void hide() {
		mouseElement.setVisible(false);
	}

	/**
	 * Sets the widget
	 */
	public static void setMouseWidget(Widget widget) {
		mouseElement.setWidget(widget);
	}

	/**
	 * Shows the mouse element
	 */
	public static void show() {
		Event evt = DOM.eventGetCurrentEvent();

		mouseElement.setPosition(DOM.eventGetClientX(evt), DOM
				.eventGetClientY(evt));
		mouseElement.setVisible(true);
	}

	/**
	 * Native event handler
	 */
	private NativePreviewHandler previewHandler = new NativePreviewHandler() {
		@Override
		public void onPreviewNativeEvent(NativePreviewEvent event) {
			switch (event.getTypeInt()) {
			case Event.ONMOUSEMOVE:
				setPosition(event.getNativeEvent().getClientX(), event
						.getNativeEvent().getClientY());
				break;
			}
		}
	};

	MouseFollower() {
		Event.addNativePreviewHandler(previewHandler);
		getElement().getStyle().setProperty("zIndex", "2000");
		setVisible(false);
		RootPanel.get().add(this, 0, 0);
	}

	protected void setPosition(int x, int y) {
		RootPanel.get().setWidgetPosition(mouseElement, x + 20, y + 20);
	}
}
